import config from "config";
import httpFetch from "share/httpFetch";
import errorMessage from "share/errorMessage";
import { messages } from "share/common";
import moment from "moment";
import exampleData from "containers/home/home.example.constant";

function createPieOptions(data, config) {
  const { title } = config;
  const options = {
    title: {
      text: title,
      subtext: data,
      left: "center",
      top: "45%", // 这边居中实在不好弄
      bottom: "center",
      textVerticalAlign: "middle",
      padding: 0,
      itemGap: 5,
      textStyle: {
        fontWeight: 400,
        fontSize: 16,
        color: "#6C788C",
        height: 16,
      },
      subtextStyle: {
        fontWeight: 400,
        fontSize: 26,
        color: "#4E5B71",
        height: 24,
      },
    },
    tooltip: {
      show: false,
    },
    legend: {
      show: false,
    },
    grid: {
      left: "1%",
      right: "1%",
      bottom: "0%",
      top: "1%",
      containLabel: true,
    },
    series: [
      {
        type: "pie",
        radius: ["55%", "65%"],
        selectedOffset: 5,
        label: {
          show: false,
        },
        labelLine: {
          show: false,
        },
        data: [
          {
            value: 0,
            selected: true,
            emphasis: {
              itemStyle: {
                color: "#1890FF",
              },
            },
          },
        ],
      },
    ],
    color: ["#1890FF", "#F1F2F5"],
  };
  const dataNum = parseFloat(data) || 0;
  options.series[0].data[0].value = dataNum;
  if (dataNum < 100) {
    options.series[0].data.push({
      value: 100 - dataNum,
      emphasis: {
        // 不加这个样式hover的时候会变白，不知道为什么
        itemStyle: {
          color: "#F1F2F5",
        },
      },
    });
  }
  return options;
}

function createBarOptions(data) {
  const colorList = ["#6CADEC", "#64A3EE", "#5A97F0", "#538FF3", "#4A82F4", "#4379F6"];
  const monthList = [];
  const valueList = [];
  if (typeof data === "object" && data) {
    Object.keys(data).forEach((key, index) => {
      const month = moment(key).format("MMM");
      monthList.push(month);
      valueList.push({
        value: data[key],
        itemStyle: {
          color: colorList[index],
        },
      });
    });
  }

  return {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
        type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
      },
    },
    grid: {
      left: "5%",
      right: "5%",
      bottom: "9%",
      top: "1%",
      containLabel: true,
    },
    xAxis: [
      {
        data: monthList,
        axisLine: {
          lineStyle: {
            color: "#DBE6F3",
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          color: "#6C788C",
          fontSize: 12,
        },
      },
    ],
    yAxis: [
      {
        type: "value",
        boundaryGap: ["0", "10%"], // 顶部留白
        splitLine: {
          lineStyle: {
            type: "dashed",
            color: "#EBF0F5",
          },
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          show: false,
        },
      },
    ],
    series: [
      {
        type: "bar",
        barWidth: 20,
        data: valueList,
      },
    ],
  };
}

function createLineOptions(data) {
  const monthList = [];
  const valueList = [];
  if (typeof data === "object" && data) {
    Object.keys(data).forEach((key, index) => {
      const month = moment(key).format("MMM");
      monthList.push(month);
      valueList.push(data[key]);
    });
  }

  return {
    tooltip: {
      trigger: "axis",
    },
    legend: {
      show: false,
    },
    grid: {
      left: "5%",
      right: "5%",
      bottom: "9%",
      top: "1%",
      containLabel: true,
    },
    xAxis: {
      data: monthList,
      axisLine: {
        lineStyle: {
          color: "#DBE6F3",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#6C788C",
        fontSize: 12,
      },
    },
    yAxis: {
      type: "value",
      boundaryGap: ["0", "10%"], // 顶部留白
      splitLine: {
        lineStyle: {
          type: "dashed",
          color: "#EBF0F5",
        },
      },
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        show: false,
      },
    },
    series: [
      {
        type: "line",
        step: "end",
        data: valueList,
      },
    ],
    color: "#4DC690",
  };
}

function handleExample(key) {
  const example = exampleData[key];
  const result = {};
  const dataArr = [];
  for (let i = 0; i < 12; i++) {
    dataArr.unshift(moment().subtract(i, "months").format("YYYY-MM"));
  }
  Object.keys(example).forEach((key) => {
    const singleData = {};
    dataArr.forEach((date, index) => {
      singleData[date] = example[key][index];
    });
    result[key] = singleData;
  });
  return new Promise((resolve) => {
    resolve({ data: result, status: 200 });
  });
}

export default {
  //获取卡片上的数据
  getData: function () {
    return new Promise((resolve, reject) => {
      httpFetch
        .get(`${config.baseUrl}/api/home/page/statistics/qty`)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err);
        });
    });
  },

  getHomeBodyData(yearMonthFilter) {
    return new Promise((resolve, reject) => {
      httpFetch
        .get(`${config.baseUrl}/api/home/page/statistics/body/qty`, {
          yearMonthFilter,
        })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err);
        });
    });
  },

  createOptions({ data, type, config }) {
    const typeMap = {
      pie: createPieOptions,
      bar: createBarOptions,
      line: createLineOptions,
    };

    const creator = typeMap[type];
    if (creator) {
      return creator(data, config);
    }
  },

  getOpenServiceData() {
    return httpFetch.get(`${config.baseUrl}/api/home/page/statistics/service/open`).catch((err) => {
      errorMessage(err.response);
      throw err;
    });
  },

  getApplicationData(params, exampleMode) {
    if (exampleMode) return handleExample("documentExample");
    return httpFetch.get(`${config.baseUrl}/api/home/page/statistics/other`, params).catch((err) => {
      errorMessage(err.response);
      throw err;
    });
  },

  getCheckInvoiceData(params, exampleMode) {
    if (exampleMode) return handleExample("invoiceExample");
    return httpFetch.get(`${config.baseUrl}/api/home/page/statistics/check/invoice`, params).catch((err) => {
      errorMessage(err.response);
      throw err;
    });
  },

  getOCRData(params, exampleMode) {
    if (exampleMode) return handleExample("orcExample");
    return httpFetch.get(`${config.baseUrl}/api/home/page/statistics/ocr`, params).catch((err) => {
      errorMessage(err.response);
      throw err;
    });
  },

  setExampleStatus(params) {
    return httpFetch.put(`${config.baseUrl}/api/user/other/setting`, params).catch((err) => {
      errorMessage(err.response);
      throw err;
    });
  },
};
